package com.huike.task;

import com.huike.domain.business.TbBusiness;
import com.huike.domain.system.SysUser;
import com.huike.mapper.TbAssignRecordMapper;
import com.huike.mapper.TbBusinessMapper;
import com.huike.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class BusinessTrackNotifyTask {

    @Autowired
    private TbBusinessMapper tbBusinessMapper;//商机
    @Autowired
    private TbAssignRecordMapper tbAssignRecordMapper; //商机跟进
    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Value("${spring.mail.username}")
    private String from;

    private static final String BUSINESS_NOTIFY_PREFIX = "business:notify:";

    @Scheduled(cron = "0 0 * * * ?")
    public void sendNotifyEmail() throws Exception {
        List<TbBusiness> tbBusinessList = tbBusinessMapper.selectTbBusinessByNextTime(LocalDateTime.now(), LocalDateTime.now().plusHours(2), "2");
        System.out.println(tbBusinessList);

        if (!CollectionUtils.isEmpty(tbBusinessList)) {
            for (TbBusiness business : tbBusinessList) {
                //查询是否已发送
                Object flag = redisTemplate.opsForValue().get(BUSINESS_NOTIFY_PREFIX + business.getId());
                if (ObjectUtils.isEmpty(flag)) {
                    //2. 查询线索跟进人的信息
                    System.out.println(business);
                    SysUser sysUser = tbAssignRecordMapper.selectByAssignIdAndType(business.getId(), "1");
                    //3. 发送提醒邮件
                    sendMail(business, sysUser);
                }
            }
        }
    }

    private void sendMail(TbBusiness business, SysUser sysUser) throws Exception {
        //发送邮件
        String text = "dioMao";
        emailUtils.sendMailWithoutAttachment(from, sysUser.getEmail(), "线索跟进提醒", text);

        log.info("发送邮件, 给指定员工: {} , 邮件正文: {}", sysUser.getEmail(), text);

        //存储已发送标识
        redisTemplate.opsForValue().set(BUSINESS_NOTIFY_PREFIX + business.getId(), "1", 150, TimeUnit.MINUTES);
    }

}
